/*
 * @Description:
 * @Author: 徐金星
 * @Date: 2020-08-26 16:54:44
 */
import axios from "axios";
import store from "../store";
import { Message } from "element-ui";
import {
  showFullScreenLoading,
  tryHideFullScreenLoading,
} from "@/utils/loading";
// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000, // request timeout
});
// request interceptor
// 不需要全局loading
const WhiteList = ["/getPubKey", "/login"];
service.interceptors.request.use(
  (config) => {
    // do something before request is sent

    // if (store.getters.token) {
    //   // let each request carry token
    //   // ['X-Token'] is a custom headers key
    //   // please modify it according to the actual situation
    //   config.headers['X-Token'] = getToken()
    // }
    WhiteList.indexOf(config.url) === -1 && showFullScreenLoading();
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    tryHideFullScreenLoading();
    const res = response.data;
    const code = parseInt(res.code);
    // 未登录返回login test
    if (res.code === "20001") {
      store.dispatch("user/resetToken").then(() => {
        location.reload();
      });
    }
    // const { url } = response.config
    // const noUrl = ['getStoreByTypes']
    // if (url.indexOf(noUrl) === -1) {
    //         if (!res.data.user) {
    //   store.dispatch('user/resetToken').then(() => {
    //   })
    // }
    // }

    // 登录接口，单独判断code
    if (response.config.url === "/shopManage/login") {
      // 账户登录未激活状态或密码已过期
      if (res.code === "20003" || res.code === "20004") {
        return res;
      }
    }

    // 修改密码接口
    if (response.config.url === "/shopManage/updatePwd") {
      // 校验失败
      if (res.code === "10003" || res.code === "30001") {
        return res;
      }
    }

    if (
      response.config.url === "/shopManage/knowledgeCategory/save" ||
      response.config.url === "/shopManage/chosenContentKeyword/save"
    ) {
      return res;
    }

    // if the custom code is not 20000, it is judged as an error.
    if (code !== 1) {
      Message({
        message: res.message || "网络请求失败,请稍后再试",
        type: "error",
        duration: 5 * 1000,
      });

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (code === 20001) {
        // to re-login
        store.dispatch("user/resetToken").then(() => {
          location.reload();
        });
        // MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
        //   confirmButtonText: 'Re-Login',
        //   cancelButtonText: 'Cancel',
        //   type: 'warning'
        // }).then(() => {

        // })
      }
      return;
    } else {
      return res;
    }
  },
  (error) => {
    tryHideFullScreenLoading();
    console.log("err" + error); // for debug
    Message({
      message:
        error.response.data.message ||
        "网络请求失败,请稍后再试" /* error.response.data.message： 获取后端返回的错误信息 */,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

export default service;
